import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/common/widget/character_count_text_field.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_video_player.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/logger/log_file_output.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/feedback/data/api/submit_feedback_api.dart';
import 'package:casdon/modules/feedback/providers/feedback_provider.dart';
import 'package:casdon/modules/feedback/ui/components/feedback_media_preview.dart';

import 'package:casdon/modules/home/data/model/unified_device_model.dart';
import 'package:casdon/modules/home/domain/states/unified_device_list_state.dart';
import 'package:casdon/modules/home/providers/home_provider.dart';

import 'package:casdon/modules/me/application/notification/oss_sts_notifier.dart';
import 'package:casdon/modules/me/application/notification/image_picker_notifier.dart';
import 'package:casdon/modules/me/application/notification/user_info_notifier.dart';

import 'package:casdon/modules/me/ui/widgets/form_field_item.dart';
import 'package:casdon/modules/lifeCircle/ui/screen/image_browser_screen.dart';

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:video_player/video_player.dart';

@RoutePage()
class FeedbackPostScreen extends ConsumerStatefulWidget {
  final String? devId;
  final bool isFromNative;

  const FeedbackPostScreen({super.key, this.devId, this.isFromNative = false});

  @override
  ConsumerState<FeedbackPostScreen> createState() => _FeedbackPostState();
}

class _FeedbackPostState extends ConsumerState<FeedbackPostScreen> {
  List<String> tags = [];
  String? selectedDeviceName;
  String? selectedDeviceId;
  String? _pendingDeviceId;
  final TextEditingController _reportReasonController = TextEditingController();
  late final TextEditingController _phoneController = TextEditingController();
  late final TextEditingController _otherDeviceController =
      TextEditingController();

  // 图片和视频
  List<File> _selectedImages = [];
  List<File> _selectedVideos = [];
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    _pendingDeviceId = widget.devId;
    _prefillContactInfo();
  }

  @override
  void dispose() {
    _reportReasonController.dispose();
    _phoneController.dispose();
    _otherDeviceController.dispose();
    super.dispose();
  }

  Future<void> _prefillContactInfo() async {
    String? contact;
    try {
      final authStorage = ref.read(authStorageProvider.notifier);
      contact = await authStorage.getUserAccount();
    } catch (e) {
      contact = null;
    }

    if ((contact == null || contact.isEmpty)) {
      try {
        final fetched = await ref
            .read(userInfoNotifierProvider.notifier)
            .fetchData();
        contact = fetched.userName;
      } catch (_) {
        contact = null;
      }
    }

    if (!mounted || contact == null || contact.isEmpty) {
      return;
    }

    _phoneController
      ..text = contact
      ..selection = TextSelection.fromPosition(
        TextPosition(offset: contact.length),
      );
  }

  @override
  Widget build(BuildContext context) {
    final deviceListAsync = ref.watch(unifiedDeviceNotifierProvider);
    return FullscreenLoadingOverlay(
      loading: _isSubmitting,
      child: Scaffold(
        appBar: CommonAppBar(
          title: "意见反馈",
          onBack: () => _trySystemBackOrNative(),
          rightActions: [
            TextButton(
              onPressed: _goMyFeedbackList,
              style: TextButton.styleFrom(
                padding: EdgeInsets.zero,
                minimumSize: Size.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),

              child: Text(
                '我的反馈',
                style: context.textTheme.bodyMedium?.copyWith(
                  color: context.colorScheme.primary,
                ),
              ),
            ),
          ],
        ),
        backgroundColor: context.colorScheme.surface,
        body: Column(
          children: [
            Expanded(
              child: SafeArea(
                bottom: false,
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(bottom: 24.h),
                  child: Container(
                    color: Colors.white,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildGap(context),
                        _buildSectionHeader(context, label: "反馈类型"),
                        Padding(
                          padding: EdgeInsets.only(
                            left: 16.w,
                            right: 12.w,
                            top: 10.h,
                            bottom: 16.h,
                          ),
                          child: _buildFeedbackTypeChips(),
                        ),
                        _buildGap(context),
                        _buildSectionHeader(context, label: "反馈内容"),
                        _buildFeedBackContent(deviceListAsync),
                        _buildGap(context),
                        FormFieldItem(
                          label: '联系方式',
                          hintText: '手机号/邮箱地址',
                          controller: _phoneController,
                          isEditable: true,
                          keyboardType: TextInputType.emailAddress,
                          textInputAction: TextInputAction.done,
                        ),
                        Container(
                          width: double.infinity,
                          height: 50.h,
                          color: context.colorScheme.surface,
                          alignment: Alignment.center,
                          child: GestureDetector(
                            onTap: _callHotline,
                            behavior: HitTestBehavior.opaque,
                            child: RichText(
                              textAlign: TextAlign.center,
                              text: TextSpan(
                                style: context.textTheme.bodyMedium?.copyWith(
                                  color: context
                                      .customColorThemeNonNull
                                      .textColor2,
                                ),
                                children: [
                                  TextSpan(
                                    text: '客服热线：',
                                    style: context.textTheme.bodyMedium
                                        ?.copyWith(
                                          color: context
                                              .customColorThemeNonNull
                                              .textColor2,
                                        ),
                                  ),
                                  TextSpan(
                                    text: '400-811-0168',
                                    style: context.textTheme.bodyMedium
                                        ?.copyWith(
                                          color: context.colorScheme.primary,
                                        ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            _buildBottomActionBar(),
          ],
        ),
      ),
    );
  }

  Future<void> _handleSubmit({bool sendLog = false}) async {
    // 验证必填字段
    if (tags.isEmpty) {
      _showError('请选择反馈类型');
      return;
    }

    if (_reportReasonController.text.trim().isEmpty) {
      _showError('请输入反馈内容');
      return;
    }

    if (_phoneController.text.trim().isEmpty) {
      _showError('请输入联系方式');
      return;
    }

    if (!_phoneController.text.trim().isEmail() &&
        !_phoneController.text.trim().isPhoneNum()) {
      _showError('联系方式错误');
      return;
    }

    if (_isSubmitting) return;

    setState(() {
      _isSubmitting = true;
    });

    try {
      // 获取设备信息
      final deviceListAsync = ref.read(unifiedDeviceNotifierProvider);
      final deviceState = deviceListAsync.valueOrNull;
      if (deviceState == null) {
        _showError('设备列表加载中，请稍后再试');
        return;
      }
      final devices = deviceState.data;
      final bool hasDevices = devices.isNotEmpty;
      final bool requiresManualDevice =
          !hasDevices || selectedDeviceName == '其他';

      if (hasDevices && selectedDeviceName == null) {
        _showError('请选择设备');
        return;
      }

      if (requiresManualDevice && _otherDeviceController.text.trim().isEmpty) {
        _showError('请输入设备名称');
        return;
      }

      String? deviceId;
      String model;

      if (requiresManualDevice) {
        model = _otherDeviceController.text.trim();
      } else {
        UnifiedDeviceModel? selectedDevice;
        if (selectedDeviceId != null) {
          for (final device in devices) {
            if (device.devId == selectedDeviceId) {
              selectedDevice = device;
              break;
            }
          }
        }
        selectedDevice ??= devices.firstWhere(
          (device) => device.name == selectedDeviceName,
          orElse: () => devices.first,
        );
        deviceId = selectedDevice.devId;
        model = selectedDevice.name;
      }

      // 上传图片和视频
      String ossIds = '';
      String videoOssIds = '';
      String logIds = '';

      if (_selectedImages.isNotEmpty || _selectedVideos.isNotEmpty) {
        final ossNotifier = ref.read(ossTokenProvider.notifier);

        // 上传图片
        if (_selectedImages.isNotEmpty) {
          final imagePaths = _selectedImages.map((f) => f.path).toList();
          final imageOssIds = await ossNotifier.uploadFiles(
            imagePaths,
            source: "feedback",
          );
          if (imageOssIds == null) return;
          ossIds = imageOssIds
              .where((id) => id != null)
              .map((id) => id!)
              .join(',');
        }

        // 上传视频
        if (_selectedVideos.isNotEmpty) {
          final videoPaths = _selectedVideos.map((f) => f.path).toList();
          final videoOssIdList = await ossNotifier.uploadFiles(
            videoPaths,
            source: "feedback",
          );
          if (videoOssIdList == null) return;
          videoOssIds = videoOssIdList
              .where((id) => id != null)
              .map((id) => id!)
              .join(',');

          ossIds = "$ossIds,$videoOssIds"; // 垃圾后端，见过的最垃圾的后端
        }

        if (sendLog == true) {
          // 上传日志：
          final logPath =
              LogFileOutput().getCurrentLogPath() ??
              await LogFileOutput().getLatestCompletedLogPath();
          if (logPath != null) {
            final logOssIds = await ossNotifier.uploadFiles([
              logPath,
            ], source: "feedback");
            if (logOssIds != null &&
                logOssIds.isNotEmpty &&
                logOssIds.first != null) {
              final logId = logOssIds.first!;
              logIds = logId;
            }
          }
        }
      }

      // 构建请求
      final request = RequestSubmitFeedbackApi(
        workOrderType: tags.first,
        title: _reportReasonController.text.trim(),
        deviceId: deviceId,
        model: model,
        contactInfo: _phoneController.text.trim(),
        ossIds: ossIds,
        errorLogOssId: logIds,
        videoOssIds: videoOssIds,
      );

      // 提交反馈
      final usecase = ref.read(submitFeedbackUsecaseProvider);
      await usecase.execute(request);

      if (mounted) {
        ToastUtil.show('感谢您的反馈，我们将不断完善体验');
        Navigator.pop(context);
      }
    } catch (e) {
      if (mounted) {
        ToastUtil.show('提交失败，请稍后重试');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  void _showError(String message) {
    ToastUtil.show(message);
  }

  void _goMyFeedbackList() {
    FeedbackListRoute().push(context);
  }

  Widget _buildBottomActionBar() {
    return Container(
      decoration: BoxDecoration(color: Colors.white),
      child: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          decoration: BoxDecoration(color: Colors.white),
          child: Row(
            children: [
              Expanded(
                child: PrimaryButton(
                  text: '提交',
                  borderRadius: 6,
                  height: 40.h,
                  textStyle: context.textTheme.bodyLarge!.copyWith(
                    color: context.colorScheme.primary,
                  ),
                  textColor: context.colorScheme.primary,
                  backgroundColor: const Color(0xFFF2F3FF),
                  onPressed: _isSubmitting
                      ? null
                      : () => _handleSubmit(sendLog: false),
                ),
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: PrimaryButton(
                  text: "发送问题日志",
                  height: 40.h,
                  onPressed: _isSubmitting
                      ? null
                      : () => _handleSubmit(sendLog: true),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGap(BuildContext context) {
    return ColoredBox(
      color: context.colorScheme.surface,
      child: SizedBox(height: 10.h, width: double.infinity),
    );
  }

  Widget _buildSectionHeader(
    BuildContext context, {
    required String label,
    bool isReuired = true,
  }) {
    return Padding(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 16.h, bottom: 0.h),
      child: Row(
        children: [
          Text(
            label,
            style: context.textTheme.headlineMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
          if (isReuired) ...[
            const SizedBox(width: 4),
            Text(
              '*',
              style: context.textTheme.headlineMedium!.copyWith(
                color: const Color(0xFFD54941),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildFeedbackTypeChips() {
    final feedbackTypesAsync = ref.watch(feedbackTypeListProvider);
    return feedbackTypesAsync.when(
      data: (options) {
        if (options.isEmpty) {
          return Text(
            '暂无反馈类型',
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          );
        }
        return Wrap(
          spacing: 8.w,
          runSpacing: 7.h,
          children: options.map((item) {
            final bool isSelected = tags.contains(item.name);
            return GestureDetector(
              onTap: () {
                setState(() {
                  tags = isSelected ? [] : [item.name];
                });
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 7.h),
                decoration: BoxDecoration(
                  color: isSelected
                      ? context.colorScheme.primary
                      : context.customColorThemeNonNull.gray2 ??
                            Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Text(
                  item.displayName,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: isSelected
                        ? Colors.white
                        : context.customColorThemeNonNull.textColor1,
                  ),
                ),
              ),
            );
          }).toList(),
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, stack) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '加载反馈类型失败',
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
          TextButton(
            onPressed: () => ref.refresh(feedbackTypeListProvider),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildDeviceChips(AsyncValue<UnifiedDeviceListState> deviceListAsync) {
    return deviceListAsync.when(
      data: (deviceState) {
        final devices = deviceState.data;
        if (_pendingDeviceId != null && devices.isNotEmpty) {
          UnifiedDeviceModel? match;
          for (final device in devices) {
            if (device.devId == _pendingDeviceId) {
              match = device;
              break;
            }
          }
          if (match != null) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (!mounted) return;
              setState(() {
                selectedDeviceId = match!.devId;
                selectedDeviceName = match.name;
                _pendingDeviceId = null;
              });
            });
          }
        }
        if (devices.isEmpty) {
          return Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text(
              '暂无绑定设备，可手动填写设备名称',
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
            ),
          );
        }

        final deviceNames = devices.map((device) => device.name).toList();
        final allOptions = [...deviceNames, '其他'];

        return SizedBox(
          height: 40.h,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            itemCount: allOptions.length,
            itemBuilder: (context, index) {
              final deviceName = allOptions[index];
              final bool isSelected = selectedDeviceName == deviceName;
              return Padding(
                padding: EdgeInsets.only(right: 8.w),
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      if (isSelected) {
                        selectedDeviceName = null;
                        selectedDeviceId = null;
                        if (deviceName == '其他') {
                          _otherDeviceController.clear();
                        }
                      } else {
                        selectedDeviceName = deviceName;
                        if (deviceName == '其他') {
                          selectedDeviceId = null;
                        } else {
                          UnifiedDeviceModel? match;
                          for (final device in devices) {
                            if (device.name == deviceName) {
                              match = device;
                              break;
                            }
                          }
                          selectedDeviceId = match?.devId;
                        }
                      }
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 10.w,
                      vertical: 7.h,
                    ),
                    decoration: BoxDecoration(
                      color: isSelected
                          ? context.colorScheme.primary
                          : context.customColorThemeNonNull.gray2 ??
                                Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Text(
                      deviceName,
                      style: context.textTheme.bodyMedium?.copyWith(
                        color: isSelected
                            ? Colors.white
                            : context.customColorThemeNonNull.textColor1,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
      loading: () => SizedBox(
        height: 40.h,
        child: const Center(child: CircularProgressIndicator()),
      ),
      error: (error, stack) => SizedBox(
        height: 40.h,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '加载设备列表失败',
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
            ),
            TextButton(
              onPressed: () => ref.refresh(unifiedDeviceNotifierProvider),
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFeedBackContent(
    AsyncValue<UnifiedDeviceListState> deviceListAsync,
  ) {
    final hasDevices = deviceListAsync.valueOrNull?.data.isNotEmpty ?? false;
    final bool showManualDeviceField =
        !hasDevices || selectedDeviceName == '其他';
    return Padding(
      padding: EdgeInsets.all(12.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildDeviceChips(deviceListAsync),
          if (showManualDeviceField) ...[
            SizedBox(height: 12.h),
            TextField(
              controller: _otherDeviceController,
              decoration: InputDecoration(
                hintText: '请输入设备名称',
                hintStyle: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor2,
                ),
                filled: true,
                fillColor:
                    context.customColorThemeNonNull.gray2 ??
                    Colors.grey.shade100,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.r),
                  borderSide: BorderSide.none,
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 12.w,
                  vertical: 12.h,
                ),
              ),
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor1,
              ),
            ),
          ],
          SizedBox(height: 12.h),
          CharacterCountTextField(
            controller: _reportReasonController,
            hintText: '请输入意见描述',
            maxLength: 500,
            maxLines: 6,
            showDoneAction: true,
          ),
          SizedBox(height: 12.h),
          Text(
            "添加图片或视频（可选，最多3个文件，其中最多1个视频，视频时长不超过30秒）",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
          SizedBox(height: 8.h),
          Builder(
            builder: (context) {
              final totalCount =
                  _selectedImages.length + _selectedVideos.length;
              return Wrap(
                spacing: 8.w,
                runSpacing: 8.h,
                alignment: WrapAlignment.start,
                crossAxisAlignment: WrapCrossAlignment.start,
                children: [
                  // 显示已选择的图片
                  ..._selectedImages.map(
                    (image) => _buildMediaPreview(
                      source: image.path,
                      isVideo: false,
                      onDelete: () {
                        setState(() {
                          _selectedImages.remove(image);
                        });
                      },
                    ),
                  ),
                  // 显示已选择的视频
                  ..._selectedVideos.map(
                    (video) => _buildMediaPreview(
                      source: video.path,
                      isVideo: true,
                      onDelete: () {
                        setState(() {
                          _selectedVideos.remove(video);
                        });
                      },
                    ),
                  ),
                  // 图片占位按钮：总文件数 < 3 时显示（最多3个文件）
                  if (totalCount < 3)
                    _buildMediaButton(
                      icon: Icons.image_outlined,
                      label: '图片',
                      onTap: _pickImages,
                    ),
                  // 视频占位按钮：视频数量 < 1 且 总文件数 < 3 时显示（最多1个视频，最多3个文件）
                  if (_selectedVideos.isEmpty && totalCount < 3)
                    _buildMediaButton(
                      icon: Icons.videocam_outlined,
                      label: '视频',
                      onTap: _pickVideos,
                    ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildMediaButton({
    required IconData icon,
    required String label,
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 68.w,
        width: 68.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(
            color:
                context.customColorThemeNonNull.gray2 ?? Colors.grey.shade300,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: context.customColorThemeNonNull.textColor2),
            SizedBox(height: 6.h),
            Text(
              label,
              style: context.textTheme.bodySmall?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMediaPreview({
    required String source,
    required bool isVideo,
    required VoidCallback onDelete,
  }) {
    return FeedbackMediaPreview(
      source: source,
      isVideo: isVideo,
      onDelete: onDelete,
      height: 68.w,
      width: 68.w,
      onTap: _handleMediaTap,
      customVideoBuilder: (path) => _VideoThumbnail(videoPath: path),
    );
  }

  void _handleMediaTap(String source, bool isVideo) {
    if (isVideo) {
      _openVideoPreview(source);
    } else {
      _openImagePreview(source);
    }
  }

  void _openImagePreview(String source) {
    List<String> images = _selectedImages.map((img) => img.path).toList();
    int initialIndex = images.indexOf(source);
    if (images.isEmpty) {
      images = [source];
      initialIndex = 0;
    } else if (initialIndex < 0) {
      images = [...images, source];
      initialIndex = images.length - 1;
    }

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) =>
            ImageBrowserScreen(imageUrls: images, initialIndex: initialIndex),
      ),
    );
  }

  void _openVideoPreview(String source) {
    final VideoSource videoSource = _isNetworkPath(source)
        ? VideoSource.network(source)
        : VideoSource.file(File(source));

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => _VideoPreviewScreen(videoSource: videoSource),
      ),
    );
  }

  bool _isNetworkPath(String path) {
    final uri = Uri.tryParse(path);
    return uri != null && uri.hasScheme && uri.host.isNotEmpty;
  }

  Future<void> _callHotline() async {
    final uri = Uri(scheme: 'tel', path: CommonConfig.servie_phone);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('无法拨打电话，请检查设备设置')));
    }
  }

  Future<void> _pickImages() async {
    final totalCount = _selectedImages.length + _selectedVideos.length;
    final remainingSlots = 3 - totalCount;
    if (remainingSlots <= 0) {
      _showError('最多只能选择3个文件');
      return;
    }

    final notifier = ref.read(imagePickerNotifierProvider.notifier);
    final result = await notifier.pickFromGallery(
      context: context,
      config: ImagePickerConfig(
        pickerType: PickerType.imageOnly,
        maxImages: remainingSlots,
      ),
    );

    if (result == null || !result.hasData || !mounted) {
      return;
    }

    setState(() {
      final remaining = 3 - (_selectedImages.length + _selectedVideos.length);
      _selectedImages.addAll(result.images.take(remaining));
    });
  }

  Future<void> _pickVideos() async {
    if (_selectedVideos.isNotEmpty) {
      _showError('最多只能选择1个视频');
      return;
    }

    final totalCount = _selectedImages.length + _selectedVideos.length;
    if (totalCount >= 3) {
      _showError('最多只能选择3个文件');
      return;
    }

    final notifier = ref.read(imagePickerNotifierProvider.notifier);
    final result = await notifier.pickFromGallery(
      context: context,
      config: const ImagePickerConfig(
        pickerType: PickerType.videoOnly,
        maxVideos: 1,
      ),
    );

    if (result == null || !result.hasData || !mounted) {
      return;
    }

    // 仅允许单个视频
    if (result.videos.length > 1) {
      _showError('最多只能选择1个视频');
      return;
    }

    setState(() {
      _selectedVideos
        ..clear()
        ..addAll(result.videos.take(1));
    });
  }

  Future<void> _trySystemBackOrNative() async {
    if (widget.isFromNative != null && widget.isFromNative == false) {
      context.router.maybePop();
      return;
    }
    // 从native页面进入时，（涂鸦设备详情页面进入）
    try {
      await const MethodChannel('native_to_flutter').invokeMethod('nativePop');
    } catch (e) {
      Log.i("native pop failed, native_to_flutter");
    }
  }
}

class _VideoPreviewScreen extends StatelessWidget {
  final VideoSource videoSource;

  const _VideoPreviewScreen({required this.videoSource});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(title: const Text('视频预览'), backgroundColor: Colors.black),
      body: SafeArea(child: VideoPlayerWidget(source: videoSource)),
    );
  }
}

// 视频缩略图组件
class _VideoThumbnail extends StatefulWidget {
  final String videoPath;

  const _VideoThumbnail({required this.videoPath});

  @override
  State<_VideoThumbnail> createState() => _VideoThumbnailState();
}

class _VideoThumbnailState extends State<_VideoThumbnail> {
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _loadThumbnail();
  }

  Future<void> _loadThumbnail() async {
    try {
      _controller = VideoPlayerController.file(File(widget.videoPath));
      await _controller!.initialize();
      // 设置视频到第一帧，但不播放
      await _controller!.seekTo(Duration.zero);
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator(strokeWidth: 2));
    }

    if (_hasError || _controller == null || !_controller!.value.isInitialized) {
      return const Center(child: Icon(Icons.videocam, size: 40));
    }

    return SizedBox.expand(
      child: FittedBox(
        fit: BoxFit.cover,
        child: SizedBox(
          width: _controller!.value.size.width,
          height: _controller!.value.size.height,
          child: VideoPlayer(_controller!),
        ),
      ),
    );
  }
}
